<html>
<head>
	<script>

		var username;
		var requestDelay;
		var notification;
		
		var unreadCounterTimer;
		var unreadNotificationTimer;
		var randomMemeTimer;
		var randomMemeIteration = 0;
		var randomMeme;
		var showRandomMeme;
		// Time before Timeout.
		var requestTimeout = 1000 * 15;
		// Time between Random Meme calls.
		var randomMemeDelay = 1000 * 60 * 10;
		
		var memeValues = { "notification": [
			{ "prop": "memes", "value": 0 },
			{ "prop": "replies", "value": 0 },
			{ "prop": "memes_private", "value": 0 },
			{ "prop": "replies_private", "value": 0 },
			{ "prop": "mentions", "value": 0 },
			{ "prop": "followers", "value": 0 }
		]};
		
		// LogLevel di Default: Nessun avviso.
		var logLevel = 0;
		// Constants for logLevel:
		var LOG_ERROR = 1;
		var LOG_WARNING = 2;
		var LOG_INFO = 3;
		var LOG_MOREINFO = 4;
		
		function init() { 

			// Initialize Username
			if( !localStorage.username || localStorage.username == "" || localStorage.username===undefined ) {
				errorHandler( "Opt" );
				return; }
			// Initialize LogLevel
			if( !localStorage.logLevel )
				localStorage.logLevel = 0;
				
			showRandomMeme = localStorage.showRandomMeme || "show";
			
			// Using local variables from the localStorage.
			username = localStorage.username;
			requestDelay = localStorage.requestDelay;
			logLevel = localStorage.logLevel;

			// Checking Request Delay validity.
			if( isNaN( requestDelay ) || requestDelay < 30 ) {
				errorHandler( "Opt" );
				return;
			}
			
			// Getting Options
			notification = localStorage.notification;
			
			if( showRandomMeme == "show" )
				getRandomMeme();
			window.setTimeout( unreadCounter, 1 * 1000 );
		}
		
		/* Log Priority manager.
		 * Log on Console only if the Priority level is Higher or Equal than logLevel setting.
		 * Using consants to better management.
		 */
		function writeLog( logText, logPriority ) {
			if( logPriority <= logLevel ) {
				if( logPriority == LOG_ERROR )
					console.error( logText );
				if( logPriority == LOG_WARNING )
					console.warn( logText);
				if( logPriority >= LOG_INFO )
					console.log( logText );
			}
		}
		
		// Getting a Random Meme from the last 30 visualized on personal Timeline to show in Popup.
		function getRandomMeme() {
			// Cleaning Timer.
			window.clearTimeout( randomMemeTimer );
			var request = new XMLHttpRequest();
			var JSONData;
			// Setting the connection timer.
			var abortTimerId = window.setTimeout( function() {
				writeLog( "Timeout Random Meme after " + requestTimeout + " seconds.", LOG_WARNING );
				request.abort();
			}, requestTimeout );
			
			request.open( "GET", getMeemiApi3Url( "wf/limit_30/html-json" ), true );
			request.onreadystatechange = function() {
				if( request.readyState == 4 )
					if( request.status == 200 ) {
						window.clearTimeout( abortTimerId );
						try { 
							// Trying to parse the Request.
							JSONData = eval( request.responseText );
							writeLog( "Random Meme retrieved", LOG_INFO );
							var randomNumber = Math.round( Math.random() * JSONData.length );
							randomMeme = JSONData[randomNumber];
							// Reset the Iteration Counters
							randomMemeIteration = 0; }
						catch( exception ) {
							// Error on parsing.
							writeLog( "Random Meme response malformed. ", LOG_ERROR );
							writeLog( request.responseText, LOG_INFO );
							// Trying 10 times to refresh with shorter timing.
							if( randomMemeIteration < 10 ) {
								randomMemeIteration ++;
								randomMemeTimer = window.setTimeout( getRandomMeme, requestTimeout ); }
							else
								randomMemeTimer = window.setTimeout( getRandomMeme, randomMemeDelay ); }}
					else
						writeLog( "Random Meme returned HTTP status: " + request.status, LOG_ERROR );
			}
			writeLog( "Sending Random Meme Request.", LOG_MOREINFO );
			request.send( null );
			randomMemeTimer = window.setTimeout( getRandomMeme, randomMemeDelay );
		}
		
		function errorHandler( badgeText ) {
			chrome.browserAction.setBadgeText({ text: badgeText });
		}
		
		function unreadCounter( ) {
			if(!localStorage.username || localStorage.username == "" || localStorage.username===undefined){ //username not set
				chrome.browserAction.setBadgeText( {text: 'Opt'} );
				return false;
			}
			// Cleaning Timer.
			window.clearTimeout( unreadCounterTimer );

			var request = new XMLHttpRequest();
			
			// Setting Timer for the Request Timeout
			var abortTimerId = window.setTimeout( function() {
				writeLog( "Unread Counter Timeout after " + requestTimeout / 1000 + " seconds.", LOG_WARNING );
				errorHandler( "TOut" );
				request.abort();
			}, requestTimeout);
			
			// Setting request for notification.
			request.open( "GET", getMeemiApiUrl( "notify" ), true );
			request.onreadystatechange = function() {

				var badgeText = "";
				if( request.readyState == 4 ) {
					window.clearTimeout( abortTimerId );
					if( request.status == 200 ) {
						// Request Done.
						if( request.responseXML ) {
							// Getting the Notify Element.
							var notifyElement = request.responseXML.getElementsByTagName( "notify" )[0];
							// Checked if exists.
							if( !notifyElement ) {
								writeLog( "Notify Document malformed.", LOG_ERROR );
								writeLog( request.responseText, LOG_INFO );
								errorHandler( "LIn" );
								return; }
							writeLog( "Notify Document retrieved.", LOG_INFO );
							writeLog( request.responseText, LOG_MOREINFO );
							var badgeValue = 0;
							
							// Parsing the Element.
							for( var index = 0, value; index < notifyElement.attributes.length; index++ ) {
								value = parseInt( notifyElement.attributes[index].nodeValue );
								memeValues.notification[index].value = value;
								if( getFlag( index ) > 0 )
									badgeValue += value;
							}
	
							if( badgeValue > 0 )
								badgeText = badgeValue.toString();
				
							chrome.browserAction.setBadgeText( {text: badgeText} ); }
						else {
							writeLog( "Unread Counter response malformed.", LOG_ERROR );
							writeLog( request.responseText, LOG_INFO );
						}}
					else
						writeLog( "Unread Counter returned HTTP status: " + request.status, LOG_ERROR );
						
					}
			}
			
			writeLog( "Sending Unread Counter request.", LOG_MOREINFO );
			request.send( null );
			unreadCounterTimer = window.setTimeout( unreadCounter, requestDelay );
		}

		function getFlag( flagPosition ) {
			if( flagPosition < 0 && flagPosition > 5 )
				return 0;
			var meemiNotification = 5 - flagPosition;
			var mask = 1 << meemiNotification;
			if(( notification & mask ) == 0 )
				return 0;
			return 1;
		}

		function getMeemiApiUrl( addings ) {
			var url = "http://meemi.com/api/" +
				username + "/" +
				addings;
			writeLog( "API2 URL requested: " + url, LOG_MOREINFO );
			return url;
		}
		
		function getMeemiApi3Url( addings ) {
			var url = "http://meemi.com/api3/" +
				username + "/" +
				addings;
			writeLog( "API3 URL requested: " + url, LOG_MOREINFO );
			return url;
		}

		function isMeemiUrl( url ) {
			return url.indexOf( "http://meemi.com/" ) == 0;
		}

		function getMeemiUrl( addings ) {
			var url = "http://meemi.com/" +
				localStorage.username + "/" +
				addings;
			return url;
		}

		chrome.tabs.onUpdated.addListener( function( tabId, changeInfo ) {
			if( changeInfo.url )
				if ( isMeemiUrl( changeInfo.url ))
					unreadCounter();
		});

		function openMeemi( selectedTab ) {
			chrome.tabs.getAllInWindow( undefined, function( tabs ) {
				for( var i = 0, tab; tab = tabs[i]; i++ ) {
					if ( tab.url && isMeemiUrl( tab.url )) {
						chrome.tabs.update(tab.id, {selected: true});
						return;
					}
				}
				chrome.tabs.create({ url: getMeemiUrl( "wf" )});
			});
		}

		chrome.browserAction.onClicked.addListener( openMeemi );
		
		chrome.extension.onRequest.addListener( function( request, sender, sendResponse ) {
			if( request.validation == "notification" )
				sendResponse( memeValues );
			else if( request.validation == "random-meme" )
				sendResponse( randomMeme );
			else
				sendResponse({}); // Empty obj, to close the request.
		});

	</script>
</head>
<body onload="init()">
</body>
</html>
